<template>
  <el-dialog :visible.sync="visible" width="520px" @close="cancel">
    <el-form :ref="formName" :model="form" :rules="rules" label-width="100px">
      <el-form-item label="附件:" prop="fileList">
        <uploadFile :file-list="form.fileList" accept-type="image/jpeg,image/png,application/pdf,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document" text="支持pdf、图片等文件" list-type="text" @handleImageSuccess="handleSuccess" />
      </el-form-item>
      <div class="dialog-footer-center">
        <span>
          <el-button type="primary" :loading="btnLoading" @click="submit">保存</el-button>
          <el-button @click="cancel">取消</el-button>
        </span>
      </div>
    </el-form>
  </el-dialog>
</template>

<script>
export default {
  name: 'UploadFileDialog',
  data() {
    return {
      formName: 'form',
      visible: false,
      info: {}, // 详情
      form: { // 表单
        fileList: []
      },
      rules: { // 规则
        fileList: [
          {
            validator(rule, value, callback) {
              if (value.length <= 0) {
                callback(new Error('请选择上传至少一个附件'))
              } else {
                callback()
              }
            },
            trigger: ['change', 'blur']
          }
        ]
      },
      btnLoading: false
    }
  },
  methods: {
    // 显示
    show(info) {
      const vm = this
      vm.info = info
      vm.visible = true
    },
    // 关闭
    cancel() {
      const vm = this
      vm.visible = false
      vm.form.fileList = []
    },
    // handel
    handleSuccess({ name, url }) {
      const vm = this
      vm.form.fileList.push({ name, url })
    },
    // 提交
    submit() {
      const vm = this
      vm.$refs.form.validate(valid => {
        if (valid) {
          vm.btnLoading = true
          const attachment = vm.form.fileList.map(e => e.url)
          const params = {
            id: vm.info.id,
            attachment
          }
          vm.$http.post('/purchase-contract/upload-attachment', params).then(res => {
            vm.$message.success('上传成功')
            vm.cancel()
            vm.btnLoading = false
          }).catch(() => {
            vm.btnLoading = false
          })
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped></style>
